package val.to.UI;

import java.util.ArrayList;

import val.to.entities.FeedItem;
import android.widget.BaseAdapter;

public abstract class ItemAdapter extends BaseAdapter {
	
	protected ArrayList<FeedItem> m_items = new ArrayList<FeedItem>();
	
	@Override
	public long getItemId(int position) {
		synchronized (m_items) {
			return m_items.get(position).getId();
		}
	}
	
	public void updateItems(ArrayList<FeedItem> newItems,
			ArrayList<Integer> deletedItems) {
		// Add the items at the beginning.
		// The first last item might be overlapping. in such case, dont add
		// it twice.
		synchronized (m_items) {
			if (deletedItems != null) {
				for (int i = m_items.size() - 1; i >= 0; --i) {
					if (deletedItems.contains(m_items.get(i).getId())) {
						m_items.remove(i);
					}
				}
			}

			m_items.addAll(0, newItems);
		}
	}

	public boolean remove(FeedItem item) {
		synchronized (m_items) {
			m_items.remove(item);
			return m_items.size() > 0;
		}
	}

	public ArrayList<FeedItem> getItems() {
		// TODO: should clone here?
		return m_items;
	}
	
	@Override
	public Object getItem(int postition) {
		synchronized (m_items) {
			return m_items.get(postition);
		}
	}
	
	@Override
	public int getCount() {
		return m_items.size();
	}

}
